package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.User;
import com.example.domain.vo.LoginUser;
import com.example.mapper.UserMapper;
import com.example.service.IUserService;
import com.example.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private AuthenticationManager authenticationManager;
       @Override
       public  Map<String,Object> login(User user){
           //1.封装Authentication对象
           UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
           //2.进行校验
           Authentication authenticate = authenticationManager.authenticate(authentication);
           //3.对authenticate进行判断
           if (Objects.isNull(authenticate)){
               throw new RuntimeException("登陆失败");
           }
           log.info(",,,,,,,,,,,,,,,,,{}",authenticate);
           //放入用户信息
           LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
           //生成jwt,使用fastjson的方法，把对象转成字符串
           String loginUserString = JSON.toJSONString(loginUser);
           String jwt = JwtUtil.createJWT(loginUserString, null);
           Map<String,Object> map = new HashMap<>();
           map.put("token",jwt);
           map.put("username",loginUser.getUsername());
           return map;
       }
}


